<template>
  <div class="app-container agricultural-container">
    <!-- 搜索栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
      class="search-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="摘要" prop="summary">
        <el-input
          v-model="queryParams.summary"
          placeholder="请输入摘要关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload" size="mini" :disabled="multiple" @click="handleBatchStatus(1)">批量上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" :disabled="multiple" @click="handleBatchStatus(0)">批量下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-star-off" size="mini" :disabled="multiple" @click="handleBatchRecommend(1)">批量推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-star-on" size="mini" :disabled="multiple" @click="handleBatchRecommend(0)">取消推荐</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="serviceList"
      @selection-change="handleSelectionChange"
      class="agricultural-table"
      stripe
      element-loading-text="加载中..."
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="摘要" prop="description" align="center" min-width="200" show-overflow-tooltip />
      <el-table-column label="图片" prop="image" align="center" width="100">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.image" 
            :src="scope.row.image" 
            alt="图片" 
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" 
          />
          <span v-else style="color: #ccc;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="价格(元)" prop="price" align="center" min-width="120">
        <template slot-scope="scope">
          <span class="price-text">￥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" prop="categoryId" align="center" min-width="120">
        <template slot-scope="scope">
          {{ scope.row.categoryName || getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" prop="phone" align="center" min-width="120" />
      <el-table-column label="微信号" prop="wechat" align="center" min-width="120" />
      <el-table-column label="服务商" prop="providerName" align="center" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="上架状态" prop="status" align="center" min-width="110">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="small" effect="dark">
            <i class="el-icon-success"></i> 已上架
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">
            <i class="el-icon-circle-close"></i> 未上架
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" prop="isRecommend" align="center" min-width="110">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isRecommend === 1" type="danger" size="small" effect="dark">
            <i class="el-icon-star-on"></i> 推荐
          </el-tag>
          <el-tag v-else type="info" size="small" effect="plain">不推荐</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="浏览数" prop="browseNum" align="center" min-width="100" />
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" style="color: #F56C6C;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number v-model="form.price" :min="0" style="width:100%" />
        </el-form-item>

        <!-- 所属分类 -->
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上传图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleLocalImage"
            accept=".jpg,.jpeg,.png"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="form.wechat" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="服务商" prop="providerName">
          <el-input v-model="form.providerName" placeholder="请输入服务商名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="4" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="上架状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">已上架</el-radio>
            <el-radio :label="0">未上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推荐" prop="isRecommend">
          <el-radio-group v-model="form.isRecommend">
            <el-radio :label="1">推荐</el-radio>
            <el-radio :label="0">不推荐</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import {
  searchWork,
  getWork,
  addWork,
  updateWork,
  delWork,
  updateWorkStatus,
  updateWorkRecommend,
  exportAgricultural
} from '@/api/yjnb/agricultural'

export default {
  name: 'Agricultural',
  data() {
    return {
      loading: false,
      showSearch: true,
      ids: [],
      multiple: true,
      total: 0,
      serviceList: [],
      open: false,
      title: '',
      categoryList: [], // 分类数据
      queryParams: {
        page: 1,
        pageSize: 10,
        title: null,
        summary: null
      },
      form: {
        id: null,
        title: null,
        price: null,
        image: null,
        phone: null,
        wechat: null,
        providerName: null,
        description: null,
        categoryId: null,
        status: 1,
        isRecommend: 0
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryList()
  },
  methods: {
    // 获取分类列表
  getCategoryList() {
  this.categoryList = [
    { id: 1, name: '耕地服务' },
    { id: 2, name: '播种服务' },
    { id: 3, name: '收获服务' },
    { id: 4, name: '病虫防治' },
    { id: 5, name: '畜牧养殖' },
    { id: 6, name: '渔业养殖' },
    { id: 7, name: '农机租赁' },
    { id: 8, name: '技术咨询' }
  ]
}

,
    getCategoryName(id) {
      const item = this.categoryList.find(i => i.id === id)
      return item ? item.name : '-'
    },
    getList() {
      this.loading = true
      // 使用搜索接口，参数使用 page 和 pageSize
      // 注意：后端搜索接口使用 description 参数，而前端使用 summary
      const { summary, ...restParams } = this.queryParams
      const searchParams = {
        ...restParams,
        description: summary || null // 将summary映射为description
      }
      searchWork(searchParams).then(res => {
        this.serviceList = res.rows
        this.total = res.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = { page: 1, pageSize: 10, title: null, summary: null }
      this.getList()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增农事服务'
    },
    handleUpdate(row) {
      this.reset()
      getWork(row.id).then(res => {
        this.form = res.data
        this.open = true
        this.title = '编辑农事服务'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const action = this.form.id ? updateWork : addWork
        action(this.form).then(() => {
          this.$message.success(this.form.id ? '修改成功' : '新增成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleDelete(row) {
      // 判断是否是有效的行对象（单个删除）
      const isValidRow = row && row.id;
      
      // 单个删除：传入单个ID；批量删除：传入ID数组
      const ids = isValidRow ? [row.id] : this.ids;
      
      // 检查是否选中了要删除的数据
      if (!ids || ids.length === 0) {
        this.$message.warning('请选择要删除的记录');
        return;
      }
      
      const message = isValidRow 
        ? `是否确认删除农事服务"${row.title}"？` 
        : `是否确认删除选中的${ids.length}条记录？`;
      
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delWork(ids);
      }).then(() => {
        this.$message.success('删除成功');
        this.getList();
      }).catch(error => {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + (error.message || error));
        }
      });
    },
    handleBatchStatus(status) {
      updateWorkStatus({ ids: this.ids, status }).then(() => {
        this.$message.success('状态更新成功')
        this.getList()
      })
    },
    handleBatchRecommend(isRecommend) {
      updateWorkRecommend({ ids: this.ids, isRecommend }).then(() => {
        this.$message.success('推荐状态更新成功')
        this.getList()
      })
    },
    /** 导出农事服务数据 */
    handleExport() {
      this.loading = true;
      exportAgricultural().then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        const timestamp = new Date().getTime();
        link.download = `农事服务数据_${timestamp}.xlsx`;
        link.click();
        window.URL.revokeObjectURL(url);
        this.loading = false;
      }).catch(() => {
        this.$message.error('导出失败');
        this.loading = false;
      });
    },
    handleLocalImage(file) {
      const rawFile = file.raw
      const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
      const isLt5M = rawFile.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$message.error('只能选择 JPG/PNG 图片！')
        return false
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB！')
        return false
      }
      const reader = new FileReader()
      reader.onload = e => {
        this.form.image = e.target.result
      }
      reader.readAsDataURL(rawFile)
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        title: null,
        price: null,
        image: null,
        phone: null,
        wechat: null,
        providerName: null,
        description: null,
        categoryId: null,
        status: 1,
        isRecommend: 0
      }
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
.agricultural-container {
  .search-form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }
  .agricultural-table {
    background: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    border-radius: 8px;
  }
  .mb8 {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;
  }
  .price-text {
    color: #E6A23C;
    font-weight: bold;
  }
}
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 6px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
</style>
